package SoundEngine
{
	import flash.display.Graphics;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;

	public class SoundObject
	{
		private static var testCount:int = 0;
		
		private var channel:SoundChannel;
		private var wPosX:Number		=	0;
		private var wPosZ:Number		=	0;
		private var wRadius:Number		=	1;
		
		public function SoundObject( wx:Number, wz:Number, radius:Number )
		{
			wPosX	=	wx;
			wPosZ	=	wz;
			wRadius	=	radius;
			
			var loader:Loader			=	new Loader();
			
			var context : LoaderContext	=	new LoaderContext();
			context.applicationDomain	=	ApplicationDomain.currentDomain;	// Loader's own ApplicationDomain
			context.securityDomain		=	null;
			
			var dispatcher : IEventDispatcher	=	loader.contentLoaderInfo;
			dispatcher.addEventListener( Event.COMPLETE, onSWFLoadComplete );
			dispatcher.addEventListener( IOErrorEvent.IO_ERROR, onSWFLoadError );
			
			loader.load( new URLRequest( "../media/swf/sfx_1.swf" ), context );
		}
		
		public function updateEar( wx:Number, wz:Number ):void
		{
			var difX:Number		=	wPosX - wx;
			var difZ:Number		=	wPosZ - wz;
			
			// Clamp to range 0->1
			var volume:Number	=	1.0 - (Math.sqrt( difX * difX + difZ * difZ ) / wRadius);
			if( volume > 1 ) volume = 1;
			else if( volume < 0 ) volume = 0;
			
			var pan:Number		=	-difX / wRadius;
			
			if( pan < -1 ) pan = -1;
			else if( pan > 1 ) pan = 1;
			
			channel.soundTransform	=	new SoundTransform( volume, pan );
		}
		
		
		
		private function onSWFLoadError( evt : IOErrorEvent ) : void
		{
			trace( "ResourceManager::SWF Load Error: " + evt.text );
		}
		
		private function onSWFLoadComplete( evt : Event ) : void
		{
			var resourceData:ApplicationDomain	=	evt.currentTarget.applicationDomain;
			
			if( testCount == 0 )
				var cls : Class					=	resourceData.getDefinition( "sfx_1_kingdom_bg_1.mp3" ) as Class;
			else
				cls								=	resourceData.getDefinition( "sfx_1_kingdom_bg_2.mp3" ) as Class;
testCount++;	
		
			var soundObj : Sound				=	(new cls) as Sound;
			var soundTrans:SoundTransform		=	new SoundTransform( 1 );
			try
			{
				channel	=	soundObj.play( 0, int.MAX_VALUE, soundTrans );
			}
			catch( ex : * ){}
		}
	}
}
